import 'package:flutter/material.dart';
import '../model/reminder.dart';
import '../service/database_service.dart';
import '../widgets/reminder_dialog.dart';

class RemindersScreen extends StatefulWidget {
  final String babyId;

  const RemindersScreen({Key? key, required this.babyId}) : super(key: key);

  @override
  _RemindersScreenState createState() => _RemindersScreenState();
}

class _RemindersScreenState extends State<RemindersScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('提醒管理')),
      body: FutureBuilder<List<Reminder>>(
        future: DatabaseService().getReminders(widget.babyId),
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return Center(child: Text('加载失败: ${snapshot.error}'));
          }

          if (!snapshot.hasData) {
            return const Center(child: CircularProgressIndicator());
          }

          final reminders = snapshot.data!;
          if (reminders.isEmpty) {
            return const Center(child: Text('暂无提醒'));
          }

          return ListView.builder(
            itemCount: reminders.length,
            itemBuilder: (context, index) {
              final reminder = reminders[index];
              return Dismissible(
                key: Key(reminder.id!),
                background: Container(
                  color: Colors.red,
                  alignment: Alignment.centerRight,
                  padding: const EdgeInsets.only(right: 16),
                  child: const Icon(Icons.delete, color: Colors.white),
                ),
                direction: DismissDirection.endToStart,
                onDismissed: (_) => _deleteReminder(reminder),
                child: ListTile(
                  leading: CircleAvatar(
                    backgroundColor: Theme.of(
                      context,
                    ).colorScheme.primary.withOpacity(0.1),
                    child: Icon(
                      reminder.type.icon,
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  title: Text(reminder.title),
                  subtitle: Text(
                    '${reminder.scheduleTime.format(context)}${reminder.repeat ? ' (每天)' : ''}\n'
                    '${reminder.notes ?? ''}',
                  ),
                  trailing: Switch(
                    value: reminder.isActive,
                    onChanged: (value) => _toggleReminder(reminder, value),
                  ),
                  onTap: () => _editReminder(reminder),
                ),
              );
            },
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        onPressed: _addReminder,
      ),
    );
  }

  Future<void> _addReminder() async {
    final result = await showDialog<Reminder>(
      context: context,
      builder: (context) => ReminderDialog(babyId: widget.babyId),
    );

    if (result != null) {
      await DatabaseService().addReminder(result);
      setState(() {});
    }
  }

  Future<void> _editReminder(Reminder reminder) async {
    final result = await showDialog<Reminder>(
      context: context,
      builder:
          (context) =>
              ReminderDialog(babyId: widget.babyId, reminder: reminder),
    );

    if (result != null) {
      await DatabaseService().updateReminder(result);
      setState(() {});
    }
  }

  Future<void> _deleteReminder(Reminder reminder) async {
    try {
      await DatabaseService().deleteReminder(reminder.id!);
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('提醒已删除')));
    } catch (e) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('删除失败: $e')));
    }
  }

  Future<void> _toggleReminder(Reminder reminder, bool value) async {
    try {
      final updated = reminder.copyWith(isActive: value);
      await DatabaseService().updateReminder(updated);
      setState(() {});
    } catch (e) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('更新失败: $e')));
    }
  }
}
